package br.com.edoc.util.converter;

import java.util.Date;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;

import br.com.edoc.excecoes.DateException;
import br.com.edoc.util.TratamentoData;
@FacesConverter( value="dateConverter" )
public class DateConverter  implements Converter{

	public Object getAsObject(FacesContext context, UIComponent componente, String value) throws ConverterException {
		// TODO Auto-generated method stub
		if(value!=null && !value.equals("")){
			if(value.trim().length()==10){
				try {
					return TratamentoData.converterStringForDateBrazilian(value);
				} catch (DateException e) {
					// TODO Auto-generated catch block
					throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Data Informada incorreta", null));
					
				}
			}else{
				throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "A data só pode ter no mínimo 10 digitos", null));
				
			}
		}
		return null;
	}

	public String getAsString(FacesContext context, UIComponent componente, Object value) throws ConverterException{
		// TODO Auto-generated method stub
		if(value!=null){
			if(value instanceof Date){
				try {
					return TratamentoData.converteDateForDateFrmtBrazilian((Date)value);
				} catch (DateException e) {
					// TODO Auto-generated catch block
					context.addMessage("Erro converter String For date", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Erro ao converter Data para String ", null));
				}
			}
		}
		return null;
	}

}
